package com.nbjtjc.safe.service.cost;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.cost.CostBudgetItemMapper;
import com.nbjtjc.safe.mapper.cost.CostBudgetMonthMapper;
import com.nbjtjc.safe.mapper.cost.CostBudgetPlanMapper;
import com.nbjtjc.safe.mapper.cost.CostBudgetSubItemMapper;
import com.nbjtjc.safe.model.cost.CostBudgetItem;
import com.nbjtjc.safe.model.cost.CostBudgetMonth;
import com.nbjtjc.safe.model.cost.CostBudgetPlan;
import com.nbjtjc.safe.model.cost.CostBudgetSubItem;
import com.nbjtjc.safe.util.MyShiroUtils;

@Service
public class CostBudgetItemService {
	@Autowired
	  private CostBudgetItemMapper costBudgetItemMapper;
	@Autowired
	  private CostBudgetSubItemMapper costBudgetSubItemMapper;
	@Autowired
	private CostBudgetPlanMapper costBudgetPlanMapper;
	@Autowired
	private CostBudgetPlanService costBudgetPlanService;
	@Autowired
	private  CostBudgetMonthMapper costBudgetMonthMapper;
	@Autowired
	  private CostBudgetSubItemService costBudgetSubItemService;
	
	@Transactional(rollbackFor = {Throwable.class})
	  public Result add(CostBudgetItem costBudgetItem){
		        Result result=new Result();
		        if(ObjectUtil.isNull(costBudgetItem)
		        		||ObjectUtil.isNull(costBudgetItem.getBudgetPlanId())
		        		){		            
		        	result.setFalse("新增内容不能为空,对应预算计划ID不能为空");
		            return result;
		        }
		        //主键为空或库中无此主键则为新建，插入数据
		        if(ObjectUtil.isNull(costBudgetItem.getId())|| ObjectUtil.isNull(costBudgetItemMapper.selectByPrimaryKey(costBudgetItem.getId()))){
		        	costBudgetItem.setItemTempId(-1);
		        	int res=costBudgetItemMapper.insertSelective(costBudgetItem);
			        if(res==0){
			            result.setFalse("新建预算项目失败");
			            return result;
			        }
			        
				      //新建月份记录 				      
				      CostBudgetMonth costBudgetMonth=new CostBudgetMonth();
				      if(ObjectUtil.isNotNull(costBudgetItem.getId())){
					      costBudgetMonth.setItemId(costBudgetItem.getId());
				      }
				      costBudgetMonth.setItemType(1);
				      if(ObjectUtil.isNotNull(costBudgetItem.getBudgetPlanId())){
				    	  costBudgetMonth.setPlanId(costBudgetItem.getBudgetPlanId());;
				    	  
					      CostBudgetPlan costBudgetPlan = costBudgetPlanMapper.selectByPrimaryKey(costBudgetItem.getBudgetPlanId());

					      if(ObjectUtil.isNotNull(costBudgetPlan)&&ObjectUtil.isNotNull(costBudgetPlan.getYear())){
				        	  costBudgetMonth.setYear(costBudgetPlan.getYear());
					      }
				      }
				      //新建月份
				      costBudgetMonthMapper.insertSelective(costBudgetMonth);
			        //插入子项目内容
			       //子项目内容不为空则插入，为空跳过无动作
//		 	    	if(CollectionUtil.isNotEmpty(costBudgetItem.getCostBudgetSubItems())){
//				        result = insertCostBudgetSubItems(costBudgetItem);
//				        if(result.isSuccess()==false){
//				            return result;
//				        }	
//				        res = costBudgetItemMapper.updateCurrentBudget(costBudgetItem.getId());
//			        	 if(res==0){
//			        		 result.setFalse("更新预算项目当前已分配预算失败");
//					         return result;
//
//			        	 }  
//		 	    	}
		        }else
		        {
		        	int res=costBudgetItemMapper.updateByPrimaryKeySelective(costBudgetItem);
		        	 if(res==0){
		        		 result.setFalse("更新预算计划失败");
				         return result;

		        	 }
		        	 //更新子项目内容
		        	 //子项目内容不为空则更新，为空跳过无动作
//		 	    	if(CollectionUtil.isNotEmpty(costBudgetItem.getCostBudgetSubItems())){
//		 	    		result= updateCostBudgetSubItems(costBudgetItem);
//				        if(result.isSuccess()==false){
//				            return result;
//				        }
//				        res = costBudgetItemMapper.updateCurrentBudget(costBudgetItem.getId());
//			        	 if(res==0){
//			        		 result.setFalse("更新预算项目当前已分配预算失败");
//					         return result;
//			        	 }
//				    }else{
//				    	res = costBudgetSubItemMapper.cancelByItemId(costBudgetItem.getId());
//			        	 if(res==0){
//			        		 result.setFalse("删除预算子项目失败");
//					         return result;
//			        	 }
//				    }
		        }

		        result.setData(costBudgetItem);

		        return result;
		    }

	    private Result insertCostBudgetSubItems(CostBudgetItem costBudgetItem){
	        Result result=new Result();

	    	//将CostBudgetItems的budgetPlanId都设为当前costBudgetPlan的ID
	    	List<CostBudgetSubItem> costBudgetSubItems =  costBudgetItem.getCostBudgetSubItems();
			for(CostBudgetSubItem subItem: costBudgetSubItems){
				subItem.setBudgetItemId(costBudgetItem.getId());
				subItem.setCancel(0);
			}
			
	    	int res=costBudgetSubItemMapper.insertList(costBudgetSubItems);
	    	if(res==0){
	            result.setFalse("插入费用预算子项目失败");
	            return result;
	        }
	    	result.setData(costBudgetSubItems);
	    	return result;
	    }
	    
	    private Result updateCostBudgetSubItems(CostBudgetItem costBudgetItem){
	        Result result=new Result();
	    	if(CollectionUtil.isEmpty(costBudgetItem.getCostBudgetSubItems())){
	            result.setFalse("更新对象为空");
	        	return result;
		    }
	    	
	    	ArrayList<Integer> costBudgetSubItemsIdDataBase = costBudgetSubItemMapper.findIdByItemId(costBudgetItem.getId());
	    	ArrayList<Integer> costBudgetSubItemsId = new ArrayList();
	    	//若库中已有该子项目（ID不为空，库中查得到）则更新，否则（该项目ID为空，或库中查不到）插入
	    	List<CostBudgetSubItem> costBudgetSubItems =  costBudgetItem.getCostBudgetSubItems();
	    
			for(CostBudgetSubItem subItem: costBudgetSubItems){
				//项目为空则跳过，继续下一个
				if(ObjectUtil.isNull(subItem)){
		            continue;
				}
				//如果ID不为空，加入costBudgetSubItems
				if(ObjectUtil.isNotNull(subItem.getId())){
					costBudgetSubItemsId.add(subItem.getId());
				}
				
				int res=0;
		    	//将subItem的BudgetItemId设为当前costBudgetItem的ID
				subItem.setBudgetItemId(costBudgetItem.getId());
				//库中已有该项目（ID不为空，库中查得到）则更新
				if(ObjectUtil.isNotNull(subItem.getId()) && ObjectUtil.isNotNull(costBudgetSubItemMapper.selectByPrimaryKey(subItem.getId()))){
					res = costBudgetSubItemMapper.updateByPrimaryKeySelective(subItem);
			    	if(res==0){
			            result.setFalse("更新费用预算子项目失败");
			            return result;
			        }
				}else{
					//（该项目ID为空，或库中查不到）插入
			    	res=costBudgetSubItemMapper.insertSelective(subItem);
			    	if(res==0){
			            result.setFalse("插入费用预算项目失败");
			            return result;
			        }
				}
			}
	        //库中有，而插入对象中没有的是要删除的子项目
			for(Integer id:costBudgetSubItemsIdDataBase){
				int res=-1;
				if(costBudgetSubItemsId.contains(id)==false){
					res = costBudgetSubItemMapper.deleteByPrimaryKey(id);
			    	if(res==0){
			            result.setFalse("删除库中费用预算子项目失败");
			            return result;
			        }
				}

			}
	    	result.setData(costBudgetSubItems);
	    	return result;
	    }
	  
	  public Result delete(int id){
	      Result result=new Result();
	      if(ObjectUtil.isNull(id)){
	          result.setFalse("删除对象不能为空");
	          return result;
	      }

	      int res = costBudgetItemMapper.deleteByPrimaryKey(id);
	      if(res==0){
	    	  result.setFalse("删除失败");
		      return result;
	      }
	      return result;
	  }
	  
	  public Result delete(CostBudgetItem costBudgetItem){
	      Result result=new Result();
	      if(ObjectUtil.isNull(costBudgetItem.getId())){
	          result.setFalse("作废对象不能为空");
	          return result;
	      }
	      
	      //获取项目下子项目完整信息,包括了月份记录
	      List<CostBudgetSubItem> costBudgetSubItems = costBudgetSubItemMapper.findDetailByItemId(costBudgetItem.getId());
	      
	      //获取大类完整信息,以得到关联的预算计划ID
	      CostBudgetItem costBudgetItemT=costBudgetItemMapper.selectByPrimaryKey(costBudgetItem.getId());
	      
	      //获取大类月份信息
          CostBudgetMonth costBudgetMonthT=new CostBudgetMonth();
          costBudgetMonthT.setItemId(costBudgetItem.getId());
          costBudgetMonthT.setItemType(1);
          CostBudgetMonth costBudgetMonthItem = costBudgetMonthMapper.selectOne(costBudgetMonthT);
          
          //获取预算计划
          if(ObjectUtil.isNotNull(costBudgetItemT)&&ObjectUtil.isNotNull(costBudgetItemT.getBudgetPlanId())){
        	  CostBudgetPlan costBudgetPlan=costBudgetPlanMapper.selectByPrimaryKey(costBudgetItemT.getBudgetPlanId());
        	  
    	      //更新预算计划汇总金额
    	      minusCostBudgetPlan(costBudgetPlan,costBudgetItemT);
          	  costBudgetPlanMapper.updateByPrimaryKeySelective(costBudgetPlan);

        	  //获取预算计划月份记录
              if(ObjectUtil.isNotNull(costBudgetPlan)&&ObjectUtil.isNotNull(costBudgetPlan.getId())){
              	CostBudgetMonth costBudgetMonthPlan=costBudgetMonthMapper.findPlanByPlanId(costBudgetPlan.getId());

      	      //更新预算计划月度金额
      	      minusCostBudgetMonth(costBudgetMonthPlan,costBudgetMonthItem);
      	      costBudgetMonthMapper.updateByPrimaryKeySelective(costBudgetMonthPlan);
      	      
              }else{
    	          result.setFalse("取月份记录时，预算计划为空");
    	          return result;
              }
          }else{
	          result.setFalse("取预算计划时，一级项目或其中的预算计划ID为空");
	          return result;
          }
	      
	      //删除大类，将costBudgetItem的删除字段置为1
	      costBudgetItem.setCancel(1);
	      int res = costBudgetItemMapper.updateByPrimaryKeySelective(costBudgetItem);
	      if(res==0){
	    	  result.setFalse("作废失败");
		      return result;
	      }
	      //删除大类月份记录
          costBudgetMonthMapper.deleteByPrimaryKey(costBudgetMonthItem.getId());
	      
	      //删除子项目
	      costBudgetSubItemMapper.cancelByItemId(costBudgetItem.getId());
	    //删除子项目月份记录
	      for(CostBudgetSubItem costBudgetSubItem:costBudgetSubItems){
	    	  CostBudgetMonth costBudgetMonthSubItem=costBudgetSubItem.getCostBudgetMonth();
	            if(ObjectUtil.isNotNull(costBudgetMonthSubItem)&&ObjectUtil.isNotNull(costBudgetMonthSubItem.getId())){
	                costBudgetMonthMapper.deleteByPrimaryKey(costBudgetMonthSubItem.getId());
	            }
	      }


	      
	      
//	      //删除子项目月份记录
////	      CostBudgetSubItem costBudgetSubItemT = new CostBudgetSubItem();
////	      costBudgetSubItemT.setBudgetItemId(costBudgetItem.getId());
////	      List<CostBudgetSubItem> costBudgetSubItems = costBudgetSubItemMapper.select(costBudgetSubItemT); 
//	      for(CostBudgetSubItem costBudgetSubItem:costBudgetSubItems){
//	      	 //删除月份记录
//	            CostBudgetMonth costBudgetMonth=new CostBudgetMonth();
//	            costBudgetMonth.setItemId(costBudgetSubItem.getId());
//	            costBudgetMonth.setItemType(2);
//	            costBudgetMonth = costBudgetMonthMapper.selectOne(costBudgetMonth);
//	            if(ObjectUtil.isNotNull(costBudgetMonth)){
//	                costBudgetMonthMapper.deleteByPrimaryKey(costBudgetMonth.getId());
//	            }
//	      }
////	      costBudgetSubItemService.delete(costBudgetSubItem);
//	      
//	     	 //删除月份记录
//          CostBudgetMonth costBudgetMonth=new CostBudgetMonth();
//          costBudgetMonth.setItemId(costBudgetItem.getId());
//          costBudgetMonth.setItemType(1);
//          costBudgetMonth = costBudgetMonthMapper.selectOne(costBudgetMonth);
//          if(ObjectUtil.isNotNull(costBudgetMonth)){
//              costBudgetMonthMapper.deleteByPrimaryKey(costBudgetMonth.getId());
//          }
//          
//          //更新记录
//          CostBudgetItem costBudgetItemR = costBudgetItemMapper.selectByPrimaryKey(costBudgetItem.getId());
//          if(ObjectUtil.isNotNull(costBudgetItemR.getBudgetPlanId())){
//        	  CostBudgetPlan costBudgetPlanT =new CostBudgetPlan();
//        	  costBudgetPlanT.setId(costBudgetItemR.getBudgetPlanId());
//              costBudgetPlanT= costBudgetPlanMapper.searchDetail(costBudgetPlanT).get(0);
//              costBudgetPlanService.calculateBudgetYear(costBudgetPlanT);
//              costBudgetPlanService.updatePlanAllItems(costBudgetPlanT);
//              costBudgetPlanService.updateMonth(costBudgetPlanT.getId());
//          }
          
	      return result;
	  }

	  
		//预算计划汇总金额减一级项目金额
		public void minusCostBudgetPlan(CostBudgetPlan costBudgetPlan,CostBudgetItem costBudgetItem){
			costBudgetPlan.setTotalBudget((ObjectUtil.isNotNull(costBudgetPlan.getTotalBudget())?costBudgetPlan.getTotalBudget():0)
					-(ObjectUtil.isNotNull(costBudgetItem.getItemTotalBudget())?costBudgetItem.getItemTotalBudget():0));
			
		}
	  
		//月份数据相减，返回减后的被减月份
		public void minusCostBudgetMonth(CostBudgetMonth costBudgetMonthA,CostBudgetMonth costBudgetMonthB){
			costBudgetMonthA.setJan((ObjectUtil.isNotNull(costBudgetMonthA.getJan())?costBudgetMonthA.getJan():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getJan())?costBudgetMonthB.getJan():0));
			costBudgetMonthA.setFeb((ObjectUtil.isNotNull(costBudgetMonthA.getFeb())?costBudgetMonthA.getFeb():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getFeb())?costBudgetMonthB.getFeb():0));
			costBudgetMonthA.setMar((ObjectUtil.isNotNull(costBudgetMonthA.getMar())?costBudgetMonthA.getMar():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getMar())?costBudgetMonthB.getMar():0));
			costBudgetMonthA.setApr((ObjectUtil.isNotNull(costBudgetMonthA.getApr())?costBudgetMonthA.getApr():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getApr())?costBudgetMonthB.getApr():0));
			costBudgetMonthA.setMay((ObjectUtil.isNotNull(costBudgetMonthA.getMay())?costBudgetMonthA.getMay():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getMay())?costBudgetMonthB.getMay():0));
			costBudgetMonthA.setJun((ObjectUtil.isNotNull(costBudgetMonthA.getJun())?costBudgetMonthA.getJun():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getJun())?costBudgetMonthB.getJun():0));
			costBudgetMonthA.setJul((ObjectUtil.isNotNull(costBudgetMonthA.getJul())?costBudgetMonthA.getJul():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getJul())?costBudgetMonthB.getJul():0));
			costBudgetMonthA.setAug((ObjectUtil.isNotNull(costBudgetMonthA.getAug())?costBudgetMonthA.getAug():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getAug())?costBudgetMonthB.getAug():0));
			costBudgetMonthA.setSep((ObjectUtil.isNotNull(costBudgetMonthA.getSep())?costBudgetMonthA.getSep():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getSep())?costBudgetMonthB.getSep():0));
			costBudgetMonthA.setOct((ObjectUtil.isNotNull(costBudgetMonthA.getOct())?costBudgetMonthA.getOct():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getOct())?costBudgetMonthB.getOct():0));
			costBudgetMonthA.setNov((ObjectUtil.isNotNull(costBudgetMonthA.getNov())?costBudgetMonthA.getNov():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getNov())?costBudgetMonthB.getNov():0));
			costBudgetMonthA.setDece((ObjectUtil.isNotNull(costBudgetMonthA.getDece())?costBudgetMonthA.getDece():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getDece())?costBudgetMonthB.getDece():0));
			costBudgetMonthA.setTotalBudget((ObjectUtil.isNotNull(costBudgetMonthA.getTotalBudget())?costBudgetMonthA.getTotalBudget():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getTotalBudget())?costBudgetMonthB.getTotalBudget():0));
			costBudgetMonthA.setTotalPlanBudget((ObjectUtil.isNotNull(costBudgetMonthA.getTotalPlanBudget())?costBudgetMonthA.getTotalPlanBudget():0)-(ObjectUtil.isNotNull(costBudgetMonthB.getTotalPlanBudget())?costBudgetMonthB.getTotalPlanBudget():0));
			
//			return costBudgetMonthA;
		}
		
	  public Result find(CostBudgetItem costBudgetItem) {
	      Result result = new Result();
	      PageHelper.startPage(costBudgetItem.getPageCurrent(), costBudgetItem.getPageSize());
	      costBudgetItem.setCancel(0);
	      List<CostBudgetItem> costBudgetSubItems = costBudgetItemMapper.select(costBudgetItem);
	      result.setData(new PageInfo<>(costBudgetSubItems));

	      return result;
	  }
	  
	  
	  public Result findByYear(@RequestBody CostBudgetPlan costBudgetPlan) {
	        Result result = new Result();
	        Integer planId = 0;
	        
	        	if(ObjectUtil.isNull(costBudgetPlan)||ObjectUtil.isNull(costBudgetPlan.getYear())){
		        	result.setFalse("年份不能为空");
		        	return result;
	        	}
		  	      if(ObjectUtil.isNull(costBudgetPlan.getDeptId())||costBudgetPlan.getDeptId()<=0){
			    	  costBudgetPlan.setDeptId(MyShiroUtils.getCompanyId());
			      }
	        	List<CostBudgetPlan> costBudgetPlans = costBudgetPlanMapper.search(costBudgetPlan);
	        	if(CollectionUtil.isEmpty(costBudgetPlans)){
		        	result.setFalse("无此年份的预算计划");
		        	return result;
	        	}else if(costBudgetPlans.size()>1){
		        	result.setFalse("此年份的预算计划有多个，请检查");
		        	return result;
	        	}else{
	        		planId=costBudgetPlans.get(0).getId();
	        	}
	        	
	        	
		  	    PageHelper.startPage(costBudgetPlan.getPageCurrent(), costBudgetPlan.getPageSize());
	        	List<CostBudgetItem>  costBudgetItems =costBudgetItemMapper.findDetailByPlanId(planId);
		        if(CollectionUtil.isEmpty(costBudgetItems)){
		        	return result;
		        }
	        	result.setData(new PageInfo<>(costBudgetItems));

	        return result;
	    }
	  
	  public Result show(int id) {
	      Result result = new Result();
	      CostBudgetItem costBudgetItem = costBudgetItemMapper.show(id);
	      result.setData(costBudgetItem);

	      return result;
	  }
}
